<template>
  <div>
    <!-- 文章表单 -->
    <!-- 标题 -->
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="标题">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <!-- 内容 -->
      <el-form-item label="内容">
        <VueEditor
          v-model="form.content"
          :useCustomImageHandler="true"
          @image-added="imgUpload"
          class="editor"
        ></VueEditor>
      </el-form-item>

      <!-- 栏目 -->
      <el-form-item label="栏目">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="category in categoryList"
            :key="category.id"
            :label="category.id"
          >{{category.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 封面 -->
      <el-form-item label="封面">
        <el-upload
          :action="$axios.defaults.baseURL+'/upload'"
          list-type="picture-card"
          :headers="{
            Authorization:'Bearer ' + token
          }"
          :on-success="coverSuccess"
          :on-remove="coverRemove"
          :file-list="form.cover"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <!-- 类型 -->
      <el-form-item label="类型">
        <el-radio-group v-model="form.type">
          <el-radio :label="1">文章</el-radio>
          <el-radio :label="2">视频</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 引入vueEditor组件库
import { VueEditor } from "vue2-editor";

export default {
  components: {
    VueEditor,
  },
  data() {
    return {
      token: localStorage.getItem("token"),
      checkList: [],
      categoryList: [],
      form: {
        title: "",
        content: "",
        categories: [],
        cover: [],
        type: 1,
      },
    };
  },
  created() {
    this.loadCategory();
    if (this.$route.query.id) {
      this.loadPost();
    }
  },
  watch: {
    // 监听多选框
    checkList() {
      this.form.categories = this.checkList.map((id) => {
        return {
          id: id,
        };
      });
    },
  },
  methods: {
    // 封装文章详情
    loadPost() {
      this.$axios({
        url: "/post/" + this.$route.query.id,
      }).then((res) => {
        console.log(res.data);
        // 处理残留的div,换成p标签,编辑器的问题
        res.data.data.content = res.data.data.content.replace(/div/g, "p");
        // 处理饿了么组件多选框数组格式
        this.checkList = res.data.data.categories.map((category) => {
          return category.id;
        });
        // 处理封面渲染问题
        res.data.data.cover = res.data.data.cover.map((img) => {
          const newImg = { ...img };
          if (newImg.url.indexOf("http") == -1) {
            // 修复不完成图片的路径
            newImg.url = this.$axios.defaults.baseURL + newImg.url;
          }
          // 处理多张图片旧文章偶尔出现uid重复;
          newImg.uid = newImg.id;
          // console.log(newImg);
          return newImg;
        });
        this.form = res.data.data;
      });
    },
    // 发起请求栏目
    loadCategory() {
      this.$axios({
        url: "/category",
      }).then((res) => {
        // console.log(res.data.data);
        this.categoryList = res.data.data.filter((category) => {
          return category.id != 0 && category.id != 999;
        });
        // console.log(this.categoryList);
      });
    },
    // 发布文章要用到
    // 图片
    coverSuccess(res, file, fileList) {
      // console.log("上传成功");
      // console.log(res,file);
      // 发布文章需要id,要将服务器的id添加到cover中
      file.id = res.data.id;
      this.form.cover.push(file);
    },
    coverRemove(file, fileList) {
      // console.log("删除图片");
      this.form.cover = fileList;
    },

    // 富文本上传图片

    // File:用户选择的图片
    // Editor:编辑框的本身
    // cursorLocation:当前光标的位置
    // resetUploader:上传完毕必须执行一个复位函数 即 resetUploader()
    imgUpload(File, Editor, cursorLocation, resetUploader) {
      // console.log("富文本上传");
      const picture = new FormData();
      picture.append("file", File);

      this.$axios({
        method: "post",
        url: "/upload",
        headers: {
          Authorization: "Bearer " + localStorage.getItem("token"),
        },
        data: picture,
      }).then((res) => {
        // console.log(res.data.data);
        // console.log(res.data.data.url);
        // 图片放入编辑器的光标所在的位置
        const url = this.$axios.defaults.baseURL + res.data.data.url;
        // 以下富文本框的固定写法
        Editor.insertEmbed(cursorLocation, "image", url);
        resetUploader();
      });
    },
    // 提交事件
    onSubmit() {
      // console.log(this.form);
      // console.log(this.checkList);
      this.$axios({
        method: "post",
        url: "/post",
        data: this.form,
      }).then((res) => {
        console.log(res.data);
        this.$router.push("/postList");
      });
    },
  },
};
</script>

<style lang="less" scoped>
.editor {
  line-height: initial;
}
.el-form-item {
  text-align: initial;
}
</style>